package com.vito.framework.system.security.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.vito.framework.base.controller.BaseController;
import com.vito.framework.base.exception.CommonException;
import com.vito.framework.cache.CacheKeys;
import com.vito.framework.cache.ICache;
import com.vito.framework.rest.bean.AppSession;
import com.vito.framework.system.menu.model.MenuBean;
import com.vito.framework.system.menu.service.impl.MenuTree;
import com.vito.framework.system.security.service.SecurityService;
import com.vito.framework.system.user.model.UserBean;
import com.vito.framework.system.user.service.UserService;
import com.vito.support.ApiResponse;
import com.vito.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***************************************************************
 * Name:        SecurityAction.java     
 * Create At:   2010-04-22
 * Module:      用户登录
 * Description: [用户登录-包括登录、首页功能]
 * Author       zhaowentao
 * ------------------------------------------------------------
 * 修改历史
 * 序号   日期                修改人              修改原因
 * 1   2012-6-19 xuyunchao   页面验证码验证
 * 2
***************************************************************/
@RestController
@RequestMapping("${frontPath}/security")
public class SecurityController extends BaseController {

	private String rand = null;//验证码
	
	@Autowired
	private SecurityService securityService;

	@Autowired
	protected ICache cacheUtil;
	@Autowired
	protected UserService userService;
	
	/**
	* Author:zhoudongxue
	* Create At:   2012-11-14
	* Description: [登录-校验验证码是否正确]
	* @return String
	 * @throws Exception 
	*/
	@RequestMapping(value = "validateCode")
	public ApiResponse validateCode(HttpServletRequest request, @RequestBody JSONObject params){
		try{
			rand = (String)request.getSession().getAttribute(CacheKeys.VALICODE);
			String input = request.getParameter("validateCode");
			if (rand==null || !rand.equals(input)) {
				return ApiResponse.ok("0");
			}else{
				return ApiResponse.ok("1");
			}
		}catch(Exception e){
			return ApiResponse.of(e);
		}
	}
	/**
	 * Author:zhaowentao
     * Create At:2010-04-22
     * Description: [登录-处理用户登录请求]
     * @return String
     */
	@PostMapping(value = "login", consumes = "application/json;charset=UTF-8")
	public ApiResponse login(@RequestBody JSONObject params, HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> _paramMap = new HashMap<>();
			_paramMap.put("param_userId", params.getString("userName"));
			_paramMap.put("param_password", params.getString("password"));

			UserBean user = securityService.login(_paramMap);
//			String ip = HttpUtil.getIpAddr(request);
			AppSession appSession= new AppSession();
			String token = IdUtil.fastSimpleUUID();
			appSession.setSessionId(token);;
			appSession.setUserId(user.getUserId());
			appSession.setUserName(user.getUserName());
			appSession.setMerchantId(user.getOrgId());
			appSession.setSource("admin");
			appSession.setLoginIp("ip");
			appSession.setHeadimg(user.getHeadImgPathShow());
			List<MenuBean> menuSet = securityService.listMenuByUserId(user.getUserId());
			List<MenuBean> menuList = MenuTree.buildDivMenuTreeData(menuSet);
			String[] menuIds = null;
			if(menuList!=null) {
				menuIds = new String[menuList.size()];
				for(int i=0;i<menuList.size();i++) {
					menuIds[i] = menuList.get(i).getMenuId();
				}
			}
			appSession.setRoleIds(menuIds);
			
			cacheUtil.put(CacheKeys.APP_TOKEN+token,appSession,60*60*24);
			request.getSession().setAttribute(CacheKeys.APP_TOKEN + token, appSession);
			CookieUtil.addCookie(response, CacheKeys.USER_TOKEN,token, 60*60*24);
			return ApiResponse.ok(token);
		} catch (CommonException e) {
			return ApiResponse.of(e);
		}

	}

	/**
	 * Author:zhaowentao
     * Create At:2010-04-22
     * Description: [登录-处理用户登录请求]
     * @return String
     */
	@PostMapping(value = "getUserInfo", consumes = "application/json;charset=UTF-8")
	public ApiResponse getUserInfo(@RequestBody JSONObject params, HttpServletRequest request, HttpServletResponse response) {
		try {
			String token =  params.getString("token");
			
			AppSession appSession = (AppSession)request.getSession().getAttribute(CacheKeys.APP_TOKEN + token);
			if(appSession==null) {
				appSession = cacheUtil.get(CacheKeys.APP_TOKEN + token);
			}
			return ApiResponse.ok(appSession);
		} catch (CommonException e) {
			return ApiResponse.of(e);
		}

	}
	/**
	 * Author:zhaowentao
     * Create At:2010-04-22
     * Description: [登录-处理用户登录请求]
     * @return String
     */
	@PostMapping(value = "logout", consumes = "application/json;charset=UTF-8")
	public ApiResponse logout(@RequestBody JSONObject params ,HttpServletRequest request, HttpServletResponse response) throws Exception {
		
    	String token = request.getHeader(CacheKeys.APP_TOKEN);
		cacheUtil.delete(CacheKeys.APP_TOKEN+token);
		request.getSession().removeAttribute(CacheKeys.APP_TOKEN+token);
		CookieUtil.addCookie(response, CacheKeys.USER_TOKEN,"", 1);
		try {
			Map<String, Object> resMap = new HashMap<>();
			return ApiResponse.ok(resMap);
		} catch (IllegalStateException e) {
			return ApiResponse.of(e);
		}
	}
}